package mblog.web.interceptor;

import java.text.MessageFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mtons.modules.lang.Const;
import mtons.modules.pojos.UserProfile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.faxsun.core.persist.entity.UserPO;
import com.faxsun.core.pojos.enums.AccountType;
import com.faxsun.core.service.UserService;
import com.faxsun.web.pojos.WechatUserInfo;
import com.faxsun.web.utils.SessionUtils;
import com.faxsun.web.utils.WechatApiUtils;

import mblog.core.pojos.User;

/**
 * 直播频道微信授权认证拦截器。仅处理访问直播url的请求，判断是否登录，若未登录，跳转到faxsun微信服务器进行登录操作
 * 
 * @author songdragon 2015年6月19日
 *
 */
public class LiveWechatInterceptor extends HandlerInterceptorAdapter {

	public static final String KEY_OPENID = "wechat_openId";
	private static final Logger log = LoggerFactory.getLogger(LiveWechatInterceptor.class);

	@Value("${local.debug}")
	private String localDebug = "true";

	@Value("${account.wechat.auth.url}")
	private String wechatAuthUrl;

	@Autowired
	private WechatApiUtils wechatApiUtils;

	@Autowired
	private UserService userService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String path = request.getRequestURI();
		String context = request.getContextPath();
		log.debug("path=" + path);
		log.debug("context=" + context);
		path = path.replace(context, "");
		log.debug("path=" + path);

		if (path.startsWith("/live/broadcast") || path.startsWith("/live/createChannel")
				|| path.startsWith("/live/modifyChannel") || path.startsWith("/live/channels")) {

			String id = path.substring(path.lastIndexOf("/") + 1);
			if (id.contains(";")) {
				id = id.substring(0, path.indexOf(";"));
			}
			if (!StringUtils.isEmpty(localDebug) && !localDebug.equals("true")) {
				// check whether is come from mobile
				Device device = DeviceUtils.getCurrentDevice(request);
				String ua = request.getHeader("User-Agent").toLowerCase();
				if (!device.isMobile() || (ua != null && !ua.contains("micromessenger"))) {
					// 非移动版或非微信浏览器，则跳转到请微信浏览器打开的静态页面
					RequestDispatcher dispatcher = request.getRequestDispatcher("/live/sharepage/" + id);
					dispatcher.forward(request, response);
					return false;
				}
			}
			Thread.sleep(500);

			HttpSession session = request.getSession();
			UserProfile up = (UserProfile) session.getAttribute(Const.KEY_LOGIN);

			log.debug("Read userprofile from session finished");
			String openId = (String) session.getAttribute(KEY_OPENID);
			log.debug("openId=" + openId);
			log.debug(session.getId());

			if (up == null && StringUtils.isEmpty(openId)) {
				// 跳转微信授权
				String url = MessageFormat.format(wechatAuthUrl, path);
				response.sendRedirect(url);
				return false;
			} else if (up == null && !StringUtils.isEmpty(openId)) {
				// 用户未登录，session中有openId，说明认证结束，跳回到本地服务器执行帐户处理
				// check db whether user exists
				up = this.userService.findByThirdId(openId, AccountType.WECHAT);
				// 获取用户信息
				WechatUserInfo wechatInfo = wechatApiUtils.getUserInfo(openId);
				if (up == null) {
					// if not exist, create user

					UserPO userPO = transformFromWechat(wechatInfo, openId);
					up = this.userService.createLocalUser(userPO);
				} else {
					// TODO: 规范置Session逻辑
					// put user info int session && update avatar,nickname and
					// lastlogin time
					User userPO = this.userService.get(up.getId());
					userPO.setLastLogin(new Date());
					userPO.setAvatar(wechatInfo.getHeadimgurl());
					userPO.setName(wechatInfo.getNickname());
					up=this.userService.update(userPO);
				}
				SessionUtils.putProfile(session, up, Boolean.TRUE);
			}
		}

		return true;
	}

	private UserPO transformFromWechat(WechatUserInfo wechatUser, String openId) {
		UserPO userPO = new UserPO();
		userPO.setAvatar(wechatUser.getHeadimgurl());
		userPO.setUsername(wechatUser.getUnionid());
		userPO.setName(wechatUser.getNickname());
		userPO.setThirdLogin(openId);
		userPO.setWechatUnionId(wechatUser.getUnionid());
		userPO.setIsLocal(1);
		userPO.setCreated(new Date());
		userPO.setRoleLevel(0);
		userPO.setLastLogin(new Date());

		return userPO;
	}

	/**
	 * 从path中解析频道id，并在wechatAuthUrl中格式化
	 * 
	 * @param wechatAuthUrl
	 * @param path
	 * @return
	 */
	public String format(String wechatAuthUrl, String path) {
		int index = path.lastIndexOf("/");
		if (index == (path.length() - 1)) {
			path = path.substring(0, path.length() - 1);
			index = path.lastIndexOf("/");
		}

		if (index >= 0) {
			String idStr = path.substring(index + 1);
			try {
				Long.parseLong(idStr);
				return MessageFormat.format(wechatAuthUrl, idStr);
			} catch (Exception e) {

			}

		}
		return "";
	}
}
